package com.nkym.wypan.listener.history;/*
 * @ClassName SearchHistoryListener
 * @Desc TODO
 * @Author 19637
 * @Date 2023/7/6 22:31
 * @Version 1.0
 */

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nkym.wypan.event.SearchEvent;
import com.nkym.wypan.model.entity.SearchHistory;
import com.nkym.wypan.service.SearchHistoryService;
import com.nkym.wypan.utils.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class SearchHistoryListener {

    @Autowired
    SearchHistoryService searchHistoryService;

    @EventListener(classes = SearchEvent.class)
    public void saveSearchHistory(SearchEvent event) {
        Long userId = event.getUserId();
        String searchContent = event.getSearchContent();

        SearchHistory searchHistory = searchHistoryService.getOne(new LambdaQueryWrapper<SearchHistory>()
                .eq(SearchHistory::getUserId, userId)
                .eq(SearchHistory::getSearchContent, searchContent)
        );
        if (searchHistory == null) {
            searchHistory = new SearchHistory();
            searchHistory.setId(IdUtils.getId());
            searchHistory.setSearchContent(searchContent);
            searchHistory.setUserId(userId);
            searchHistoryService.save(searchHistory);
            return;
        }
        //如果存在相同搜索历史 则更新搜索时间
        searchHistory.setUpdateTime(new Date());
        searchHistoryService.updateById(searchHistory);
    }

}
